import { useEffect, useState } from 'react';

import { Button, Col, Form, Image, Input, Popconfirm, Row, Select, Space, Table } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { Org, QueryOrgListParams } from './services';
import { queryOrgList, delOrg, OrgStatus, OrgType } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import { enum2options } from '@/utils/enum2options';
import Operations from '@/components/Operations';
import dayjs from 'dayjs';
import { jump2target } from '@/utils/common';

const OrgPage: React.FC = () => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<QueryOrgListParams>()
  const [searchParams, setSearchParams] = useState<QueryOrgListParams>({
    pageNum: 1, pageSize: 10,
  });
  const roleList = useRequest(() => queryOrgList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delOrgAsync } = useRequest(delOrg, {manual: true})

  const onFinish = (formValues: QueryOrgListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const openEditPage = (title: string, type: string, roleId?: number) => {
    jump2target(`/station/org/edit?type=${type}&id=${roleId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/station/org/edit_title', title)
  }

  const openDetailPage = (title: string, type: string, roleId?: number) => {
    jump2target(`/station/org/detail?type=${type}&id=${roleId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/station/org/detail_title', title)
  }

  const jump2stationListPage = (record: Org) => {
    jump2target(`/station/stationList?orgId=${record.id}&orgName=${record.orgName}`, {needRefresh: true})
  }

  const columns: ColumnsType<Org> = [
    {
      title: '名称',
      width: 160,
      dataIndex: 'orgName',
      render: (val, record) => {
        if (record.orgType === OrgType.个人) return record.username || '--'
        return val || '--'
      }
    },
    {
      title: '类型',
      width: 100,
      dataIndex: 'orgType',
      render: val => val && OrgType[val],
    },
    {
      title: '公司税号/个人身份证号',
      width: 190,
      dataIndex: 'companyCode',
      render: (val, record) => {
        if (record.orgType === OrgType.个人) return record.idCode || '--'
        return val || '--'
      }
    },
    {
      title: '分成比例',
      width: 120,
      dataIndex: 'moneyRate',
      render: val => (val || 0 ) * 100,
    },
    {
      title: '资质图片',
      width: 100,
      dataIndex: 'companyPic',
      render: (val, record) => {
        if (record.orgType === OrgType.个人 && record.idImg) return <Image src={record.idImg} style={{width: 60, height: 40}} />
        if (record.orgType === OrgType.企业 && val) return <Image src={val} style={{width: 60, height: 40}} />
        return '--'
      },
    },
    {
      title: '法人姓名',
      width: 100,
      dataIndex: 'username',
      render: val => val || '--'
    },
    {
      title: '法人身份证',
      width: 110,
      dataIndex: 'idImg',
      render: (val, record) => {
        if (record.orgType === OrgType.企业 && val) return <Image src={val} style={{width: 60, height: 40}} />
        return '--'
      },
    },
    {
      title: '管理员姓名',
      width: 110,
      dataIndex: 'nickname',
      render: val => val || '--'
    },
    {
      title: '管理员手机号',
      width: 110,
      dataIndex: 'telephone',
      render: val => val || '--'
    },
    {
      title: '公司地址',
      width: 200,
      dataIndex: 'companyAddress',
      render: val => val || '--'
    },
    {
      title: '创建时间',
      width: 140,
      dataIndex: 'createTime',
      render: val => val ? dayjs(val).format('YYYY-MM-DD') : '--',
    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'status',
      render: status => status && OrgStatus[status],
    },
    {
      title: '操作',
      key: 'operation',
      width: 170,
      fixed: 'right',
      render: (_, record) => {
        return <Operations>
          <a onClick={() => openDetailPage('经销商详情', 'edit', record.id)}>详情</a>
          <Access accessible={access.编辑 || true}>
            <a onClick={() => openEditPage('编辑经销商', 'edit', record.id)}>编辑</a>
          </Access>
          <Access accessible={record.status === OrgStatus.禁用}>
            <Popconfirm
              title={`确定启用: ${record.orgName} 吗?`}
              onConfirm={() => delOrgAsync({businessId: record.id, status: OrgStatus.启用}).then(roleList.refresh)}
              okText="启用"
              cancelText="取消"
            >
              <a>启用</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.status === OrgStatus.启用}>
            <Popconfirm
              title={`确定禁用: ${record.orgName} 吗?`}
              onConfirm={() => delOrgAsync({businessId: record.id, status: OrgStatus.禁用}).then(roleList.refresh)}
              okText="禁用"
              cancelText="取消"
            >
              <a>禁用</a>
            </Popconfirm>
          </Access>
          <a onClick={() => jump2stationListPage(record)}>场站</a>
          <Access accessible={access.删除 || true}>
            <Popconfirm
              title={`确定删除: ${record.orgName} 吗?`}
              onConfirm={() => delOrgAsync({businessId: record.id, status: 3}).then(roleList.refresh)}
              okText="删除"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>
        </Operations>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      roleList.refresh()
    }
    window.addEventListener('refreshOrgList', refresh)
    return () => {
      window.removeEventListener('refreshOrgList', refresh)
    }
  }, []);

  return (
    <div className='container'>
      <div className="card search-card">
        <div className="toolbar">
          <Space>
            <Access accessible={!!access.orgAdd}>
              <Button type='primary' onClick={() => openEditPage('添加经销商', 'edit')}>添加经销商</Button>
            </Access>
          </Space>
        </div>
        <div className="form-area">
          <Form name='searchOrgForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='名称' name='username'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='管理员账号' name='telephone'>
                  <Input placeholder='请输入手机号' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(OrgStatus)} style={{width: '100%'}} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='企业类型' name='orgType'>
                  <Select placeholder='请选择' options={enum2options(OrgType)} style={{width: '100%'}} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={roleList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Org>
          rowKey='id'
          loading={roleList.loading}
          dataSource={roleList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: roleList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default OrgPage;
